package com.yangtzeu.jwc.activity;

import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.businessservice.BusinessHttpCallBack;
import com.yangtzeu.jwc.businessservice.impl.StudentServiceImpl;
import com.yangtzeu.jwc.customview.CustomeProgressDialog;
import com.yangtzeu.jwc.domain.Course;
import com.yangtzeu.jwc.domain.XkInfo;
import com.yangtzeu.jwc.utils.ConfirmDialog;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.L;

@SuppressWarnings("rawtypes")
@SuppressLint({ "HandlerLeak", "InflateParams" })
public class GxkActivity extends BaseActivity {
    private Map gxkInfo;
    private ListView gxCourseList;
    private List<Course> gxkList;
    private XkInfo xkInfo;
    private CustomeProgressDialog dialog;
    private String resultMsg;
    private BaseAdapter adapter;
    private int lbGxCount;

    private static final int SHOWPROGRESSDIALOG = 0;
    private static final int DISMISSDIALOG = 1;
    private static final int LOADINGFAILED = 2;
    private static final int LOADINGGXKLISTFINISHED = 3;
    private static final int SELECTGXKFINISHED = 4;

    private Handler myHandler = new Handler() {

	@SuppressWarnings("unchecked")
	@Override
	public void handleMessage(Message msg) {
	    switch (msg.what) {
	    case SHOWPROGRESSDIALOG:
		dialog = CustomeProgressDialog.show(GxkActivity.this, "正在添加...");
		break;
	    case DISMISSDIALOG:
		if (dialog != null) {
		    dialog.dismiss();
		}
		break;
	    case LOADINGFAILED:
		myHandler.sendEmptyMessage(DISMISSDIALOG);
		String failureMsg = msg.getData().getString("msg");
		MyApplication.getInstance().showShortToast(failureMsg);
		break;
	    case SELECTGXKFINISHED:
		if (resultMsg != null) {
		    getGxkList();
		} else {
		    Toast.makeText(getApplicationContext(), "选课错误:" + resultMsg, Toast.LENGTH_LONG).show();
		}
		break;
	    case LOADINGGXKLISTFINISHED:
		int last_lbGxkCount = lbGxCount;
		L.d("上一次公选课数量" + last_lbGxkCount);
		xkInfo = (XkInfo) gxkInfo.get("xkInfo");
		gxkList = (List<Course>) gxkInfo.get("gxkList");
		if (gxkList != null) {
		    Collections.sort(gxkList, new GxkComparator());
		    adapter.notifyDataSetChanged();
		}
		try {
		    lbGxCount = Integer.parseInt(xkInfo.getLbGxCount());
		} catch (NumberFormatException e) {
		    lbGxCount = 0;
		}
		L.d(last_lbGxkCount + "本次公选课数量" + lbGxCount);
		if (lbGxCount > last_lbGxkCount) {
		    Toast.makeText(GxkActivity.this, "添加成功,请到已选课程里面查看已选信息!", Toast.LENGTH_LONG).show();
		} else {
		    Toast.makeText(GxkActivity.this, "添加失败,人数已满或该课程已经添加!", Toast.LENGTH_LONG).show();
		}
		break;
	    default:
		break;
	    }
	}

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
    }

    @Override
    public void setView() {
	super.setView();
	setContentView(R.layout.activity_gxk);
    }

    @Override
    @SuppressWarnings("unchecked")
    public void initData() {
	super.initData();
	Intent itt = getIntent();
	xkInfo = (XkInfo) itt.getSerializableExtra("xkInfo");
	gxkList = (List<Course>) itt.getSerializableExtra("gxkList");
	try {
	    lbGxCount = Integer.parseInt(xkInfo.getLbGxCount());
	} catch (NumberFormatException e) {
	    lbGxCount = 0;
	}
	L.d("公选课数量" + gxkList.size());
	Collections.sort(gxkList, new GxkComparator());
    }

    @Override
    public void initActionBar() {
	super.initActionBar();
	setSimpleActionBar(null, "选修公选课", null, null);
    }

    @Override
    public void initView() {
	super.initView();
	gxCourseList = (ListView) findViewById(R.id.gxCourseList);
    }

    @Override
    public void initListener() {
	super.initListener();
    }

    @Override
    public void initAdapter() {
	super.initAdapter();
	adapter = new gxCourseListAdapter();
	gxCourseList.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
	super.onClick(v);
    }

    class GxkComparator implements Comparator<Course> {
	Collator collator = Collator.getInstance(java.util.Locale.CHINA);

	@Override
	public int compare(Course arg0, Course arg1) {
	    Course c0 = arg0;
	    Course c1 = arg1;

	    // 可选的排在前面
	    String canSelect1 = c0.isCanSelect() + "";
	    String canSelect2 = c1.isCanSelect() + "";
	    int flag = collator.getCollationKey(canSelect2).compareTo(collator.getCollationKey(canSelect1));
	    // int flag = sc0.getCname().compareTo(sc1.getCname());
	    if (flag == 0) {
		return collator.getCollationKey(c0.getCname()).compareTo(collator.getCollationKey(c1.getCname()));
	    } else {
		return flag;
	    }
	}
    }

    /**
     * 选修公选课
     */
    private void xxGxk(String courseId) {
	myHandler.sendEmptyMessage(SHOWPROGRESSDIALOG);
	StudentServiceImpl.getInstance().xxGxk(courseId, new BusinessHttpCallBack() {
	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		Message msg = myHandler.obtainMessage();
		msg.what = LOADINGFAILED;
		msg.getData().putString("msg", failuremsg);
		myHandler.sendMessage(msg);
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
		resultMsg = (String) obj;
		myHandler.sendEmptyMessage(SELECTGXKFINISHED);
	    }

	});
    }

    private void getGxkList() {
	StudentServiceImpl.getInstance().getGxk(xkInfo.getSelectedXiaoqu(), new BusinessHttpCallBack() {
	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		Message msg = myHandler.obtainMessage();
		msg.what = LOADINGFAILED;
		msg.getData().putString("msg", failuremsg);
		myHandler.sendEmptyMessage(DISMISSDIALOG);
		myHandler.sendMessage(msg);
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
		gxkInfo = (Map) obj;
		myHandler.sendEmptyMessage(DISMISSDIALOG);
		myHandler.sendEmptyMessage(LOADINGGXKLISTFINISHED);
	    }

	});
    }

    private final class gxCourseListAdapter extends BaseAdapter {
	LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	@Override
	public int getCount() {
	    // TODO Auto-generated method stub
	    return gxkList.size();
	}

	@Override
	public Object getItem(int position) {
	    // TODO Auto-generated method stub
	    return gxkList.get(position);
	}

	@Override
	public long getItemId(int position) {
	    // TODO Auto-generated method stub
	    return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	    // TODO Auto-generated method stub
	    if (convertView == null) {
		convertView = inflater.inflate(R.layout.gxk_item, null);
	    }
	    final Course c = (Course) getItem(position);
	    TextView gxk_cname = (TextView) convertView.findViewById(R.id.gxk_cname);
	    gxk_cname.setText(c.getCname());
	    TextView gxk_ccredit = (TextView) convertView.findViewById(R.id.gxk_ccredit);
	    gxk_ccredit.setText(c.getCredit());
	    TextView gxk_time = (TextView) convertView.findViewById(R.id.gxk_time);
	    gxk_time.setText(c.getTime());
	    TextView gxk_maxSelect = (TextView) convertView.findViewById(R.id.gxk_maxSelect);
	    gxk_maxSelect.setText(c.getMaxCount());
	    TextView gxk_selectedcount = (TextView) convertView.findViewById(R.id.gxk_selectedcount);
	    gxk_selectedcount.setText(c.getCount());
	    TextView gxk_mark = (TextView) convertView.findViewById(R.id.gxk_mark);
	    gxk_mark.setText(c.getClass1());// 备注
	    Button selectBtn = (Button) convertView.findViewById(R.id.gxk_selectBtn);
	    if (!c.isCanSelect()) {
		selectBtn.setVisibility(View.INVISIBLE);
		selectBtn.setEnabled(false);
		selectBtn.setTextColor(Color.rgb(125, 125, 125));
	    } else {
		selectBtn.setVisibility(View.VISIBLE);
		selectBtn.setEnabled(true);
		selectBtn.setTextColor(Color.rgb(255, 255, 255));
		selectBtn.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			if (lbGxCount >= 2) {
			    Toast.makeText(GxkActivity.this, "您已经超过了公选修课能选修的最大门次!,请前往选修课查询页面删除后再次添加!", Toast.LENGTH_LONG).show();
			} else if (ConfirmDialog.show(GxkActivity.this, "提示", "确定添加:" + c.getCname() + "?")) {
			    xxGxk(c.getId());
			}
		    }
		});
	    }
	    return convertView;
	}

    }
}
